#include "uid.h"

int uid_init(uid_pool *pool, int first_id)
{
	if (first_id > UID_ID_MAX)
	{
		return UID_INVALID;
	}
	pool->next_id = first_id;
	return UID_SUCCESS;
}

int uid_next(uid_pool *pool, int *id)
{
	*id = pool->next_id;
	if (pool->next_id == UID_UNDEFINED)
	{
		return UID_EXHAUSTED;
	}
	return UID_SUCCESS;
}

int uid_reserve(uid_pool *pool, int id)
{
	if (id > UID_ID_MAX)
	{
		return UID_INVALID;
	}
	if (id < pool->next_id)
	{
		return UID_INVALID;
	}
	if (pool->next_id == UID_ID_MAX)
	{
		pool->next_id = UID_UNDEFINED;
	}
	else
	{
		pool->next_id = id + 1;
	}
	return UID_SUCCESS;
}

int uid_reserve_next(uid_pool *pool, int *id)
{
	*id = pool->next_id;
	if (pool->next_id == UID_UNDEFINED)
	{
		return UID_EXHAUSTED;
	}
	else
	{
		if (pool->next_id == UID_ID_MAX)
		{
			pool->next_id = UID_UNDEFINED;
		}
		else
		{
			pool->next_id += 1;
		}
	}
	return UID_SUCCESS;
}
